
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>在线文件管理</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;"/>
<script src="js/jquery.js"></script>
<style>
body{margin: 0;}

.fileBox{/*margin:50px;*/}
.fileInputP{display:inline-block;width:200px;height:30px;border-radius:5px;overflow:hidden;position:relative;}
.fileInputP i{
    display: inline-block;
    width: 200px;
    height: 30px;
    color: #3e2ec1;
    background: #8fff82;
    text-align: center;
    line-height: 30px;
}
#fileInput{position:absolute;left:0;top:0;right:0;bottom:0;opacity:0;}
#fileSpan{display:inline-block;width:300px;height:150px;border:2px dashed #ccc;text-align:center;line-height:150px;}

.fileList_parent{margin:50px;display:none;}
.fileList_parent th{background:#dadada;font-weight:bold;}
.fileList_parent th,.fileList_parent td{padding:5px;}
.fileList tr:nth-of-type(2n){background:#dadada;}

.progressParent{width:200px;height:20px;border-radius:5px;background:#ccc;overflow:hidden;position:relative;}
.progress{width:0%;height:20px;background:#7d8f33;}
.progressNum{display:inline-block;width:100%;height:20px;text-align:center;line-height:20px;color:#fff;position:absolute;left:0;top:0;}

#fileBtn{margin-left:50px;display:none;}



  .container {
    padding: 20px;
    min-height: 500px;
    /* margin: 100px 100px 20px; */
    border: 1px solid #ddd;
    /* text-align: center;*/
  }

        .select-box-container {
            -webkit-touch-callout: none;
            -webkit-user-select: none;
            -khtml-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
        }

        .select-box-container .toggle-all-container {
            margin-bottom: 25px;
        }

        .select-item {
            display: inline-block;
            width: 100px;
            height: 100px;
            text-align: center;
            line-height: 100px;
            font-size: 12px;
            border: 1px solid #ccc;
            margin-right: 10px;
            margin-bottom: 10px;
            cursor: pointer;
            overflow: hidden;
        }
        .select-item.selected,
        .select-item.temp-selected {
            background-color: #ddd;
        }
        .select-box-dashed {
            position: absolute;
            display: none;
            width: 0px;
            height: 0px;
            padding: 0px;
            margin: 0px;
            border: 1px dashed #0099ff;
            background-color: #c3d5ed;
            opacity: 0.5;
            filter: alpha(opacity=50);
            font-size: 0px;
            z-index: 99999;
            pointer-events: none;
        }
.fileDiv{
    position: relative;
}
.image{
    width:100%;
}
.temp-selected .image{
        opacity: 0.5;
}
.selected .image{
        opacity: 0.5;
}
.image-text {
    position: absolute;
    bottom: 0;
    width: 100%;
    text-align: center;
    height: 15px;
    z-index: 5;
    line-height: 15px;
    background-color: rgb(214 214 214 / 68%);
}
</style>

</head>
<body>
<div id="toggle-all-container">
<!--<a href="javascript:;" class="btn btn-md btn-default" id="toggle-all-btn">全选/取消全选</a>-->
<!--<a href="javascript:;" class="btn btn-md btn-default" id="refeash">刷新文件</a>-->
<a href="javascript:;" class="btn btn-md btn-default" id="delete" style="margin-right: 10px;">删除</a>
<a href="javascript:;" class="btn btn-md btn-default" id="rename" style="margin-right: 10px;">重命名</a>
<p class="fileInputP vm">
<i>上传文件</i>
<input type="file" multiple id="fileInput" />
</p>

</div>
<div class="fileBox"  >

<div class="mask"></div>


</div>

<div class="container fileSpan"   id="select-box-container">



</div>

<h4>选中文件：</h4>
<div id="data"></div>

<table width="50%" border="1" class="fileList_parent">
<thead>
<tr>
<th>书名</th>
<th>类型</th>
<th>大小</th>
<th>私藏</th>
<th>进度</th>
<th>操作</th>
</tr>
</thead>
<tbody class="fileList">

</tbody>
</table>
<input type="button" value="上传" id="fileBtn" />



<script>
$(function(){
	
    var baseFilePath = 'files/';
        
	//元素
	var oFileBox = $(".fileBox");					//选择文件父级盒子
	var oFileInput = $("#fileInput");				//选择文件按钮
	var oFileSpan = $(".fileSpan");					//选择文件框

	var oFileList_parent = $(".fileList_parent");	//表格
	var oFileList = $(".fileList");					//表格tbody
	var oFileBtn = $("#fileBtn");					//上传按钮
	
	var flieList = [];								//数据，为一个复合数组
	var sizeObj = [];								//存放每个文件大小的数组，用来比较去重
	var domain = window.location.protocol+"//"+window.location.host + window.location.pathname;
	
	//拖拽外部文件，进入目标元素触发
	oFileSpan.on("dragenter",function(){
		//$(this).text("可以释放鼠标了！");
		$(this).css("background","#ccc");
	});

	//拖拽外部文件，进入目标、离开目标之间，连续触发
	oFileSpan.on("dragover",function(){
		return false;
	});

	//拖拽外部文件，离开目标元素触发
	oFileSpan.on("dragleave",function(){
        //$(this).text("请将文件拖到此处");
		$(this).css("background","none");
	});

	//拖拽外部文件，在目标元素上释放鼠标触发
	oFileSpan.on("drop",function(ev){
		var fs = ev.originalEvent.dataTransfer.files;
		analysisList(fs);		//解析列表函数
		//$(this).text("请将文件拖到此处");
		$(this).css("background","none");
        uploadFunc();
		return false;
	});

	//点击选择文件按钮选文件
	oFileInput.on("change",function(){
		analysisList(this.files);
        uploadFunc();
	})
	
	//解析列表函数
	function analysisList(obj){
		//如果没有文件
		if( obj.length<1 ){
			return false;
		}
		
		for( var i=0;i<obj.length;i++ ){

			var fileObj = obj[i];		//单个文件
			var name = fileObj.name;	//文件名
			var size = fileObj.size;	//文件大小
			var type = fileType(name);	//文件类型，获取的是文件的后缀
			
			//文件大于1024M，就不上传
			if( size > 1024*1024*1024 || size == 0 ){
				alert('“'+ name +'”超过了1024M，不能上传');
				continue;
			}
			
			//文件类型不为这三种，就不上传
			/*if( ("pdf/txt/epub").indexOf(type) == -1 ){
				alert('“'+ name +'”文件类型不对，不能上传');
				continue;
			}*/
			
			//把文件大小放到一个数组中，然后再去比较，如果有比较上的，就认为重复了，不能上传
			if( sizeObj.indexOf(size) != -1 ){
				alert('“'+ name +'”已经选择，不能重复上传');
				continue;
			}
			
			//给json对象添加内容，得到选择的文件的数据
			var itemArr = [fileObj,name,size,type];	//文件，文件名，文件大小，文件类型
			flieList.push(itemArr);
			
			//把这个文件的大小放进数组中
			sizeObj.push(size);
			
		}
		
		//console.log(flieList)
		//console.log(sizeObj)
		createList()				//生成列表
		oFileList_parent.show();	//表格显示
		//oFileBtn.show();			//上传按钮显示
	};
	
		
	//生成列表
	function createList(){
		oFileList.empty();					//先清空元素内容
		for( var i=0;i<flieList.length;i++ ){
			
			var fileData = flieList[i];		//flieList数组中的某一个
			var objData = fileData[0];		//文件
			var name = fileData[1];			//文件名
			var size = fileData[2];			//文件大小
			var type = fileData[3];			//文件类型
			var volume = bytesToSize(size);	//文件大小格式化
			
			
			var oTr = $("<tr></tr>");
			var str = '<td><cite title="'+ name +'">'+ name +'</cite></td>';
			str += '<td>'+ type +'</td>';
			str += '<td>'+ volume +'</td>';
			str += '<td><input type="radio" /></td>';
			str += '<td>';
			str += '<div class="progressParent">';
			str += '<p class="progress"></p>';
			str += '<span class="progressNum">0%</span>';
			str += '</div>';
			str += '</td>';
			str += '<td><a href="javascript:;" class="operation">删除</a></td>';
			
			oTr.html(str);
			oTr.appendTo( oFileList );
		}
	}
	
	//删除表格行
	oFileList.on("click","a.operation",function(){
		var oTr = $(this).parents("tr");
		var index = oTr.index();
		oTr.remove();		//删除这一行
		flieList.splice(index,1);	//删除数据
		sizeObj.splice(index,1);	//删除文件大小数组中的项
		
		//console.log(flieList);
		//console.log(sizeObj);
		
	});
	
	var uploadFunc = function(){
		oFileBtn.off();
		var tr = oFileList.find("tr");		//获取所有tr列表
		var successNum = 0;					//已上传成功的数目
		oFileList.off();					//取消删除事件
		//oFileBox.slideUp();					//隐藏输入框
		oFileList.find("a.operation").text("等待上传");
		
		
		for( var i=0;i<tr.length;i++ ){
			uploadFn(tr.eq(i),i);		//参数为当前项，下标
		}
				
		function uploadFn(obj,i){
			
			var formData = new FormData();
			var arrNow = flieList[i];						//获取数据数组的当前项
			
			// 从当前项中获取上传文件，放到 formData对象里面，formData参数以key name的方式
			var result = arrNow[0];							//数据
			formData.append("imageFile" , result);
			
			var name = arrNow[1];							//文件名
			formData.append("email" , name);
			
			var progress = obj.find(".progress");			//上传进度背景元素
			var progressNum = obj.find(".progressNum");		//上传进度元素文字
			var oOperation = obj.find("a.operation");		//按钮
			
			oOperation.text("正在上传");							//改变操作按钮
			oOperation.off();
			
			var request = $.ajax({
				type: "POST",
				url: "upload.php",
				data: formData,			//这里上传的数据使用了formData 对象
				processData : false, 	//必须false才会自动加上正确的Content-Type
				contentType : false,
				
				//这里我们先拿到jQuery产生的XMLHttpRequest对象，为其增加 progress 事件绑定，然后再返回交给ajax使用
				xhr: function(){
					var xhr = $.ajaxSettings.xhr();
					if(onprogress && xhr.upload) {
						xhr.upload.addEventListener("progress" , onprogress, false);　
						return xhr;
					}
				},
				
				//上传成功后回调
				success: function(){
					oOperation.text("成功");
					successNum++;
					console.log(successNum);
                    refeashFiles();
                    getSelectFiles();
                    /*
					if(successNum == tr.length){
						open("http://www.baidu.com","_self");	//如果全部传成功了，跳转
					}
                    */
				},
				
				//上传失败后回调
				error: function(){
					oOperation.text("重传");
					oOperation.on("click",function(){
						request.abort();		//终止本次
						uploadFn(obj,i);
					});
				}
				
			});
			
			
			//侦查附件上传情况 ,这个方法大概0.05-0.1秒执行一次
			function onprogress(evt){
				var loaded = evt.loaded;	//已经上传大小情况  
				var tot = evt.total;		//附件总大小  
				var per = Math.floor(100*loaded/tot);  //已经上传的百分比
				progressNum.html( per +"%" ); 
				progress.css("width" , per +"%");
			}
		
		}			
		
				
	};
    
	//上传
	oFileBtn.on("click",uploadFunc);
	
	



//字节大小转换，参数为b
function bytesToSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB'];
    if (bytes == 0) return 'n/a';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};

//通过文件名，返回文件的后缀名
function fileType(name){
	var nameArr = name.split(".");
	return nameArr[nameArr.length-1].toLowerCase();
}





  var initSelectBox = function(selector, selectCallback) {
            function clearBubble(e) {
                if (e.stopPropagation) {
                    e.stopPropagation();
                } else {
                    e.cancelBubble = true;
                }

                if (e.preventDefault) {
                    e.preventDefault();
                } else {
                    e.returnValue = false;
                }
            }
            var $container = $(selector);
            $(".select-box-dashed").remove();
            var $selectBoxDashed = $('<div class="select-box-dashed"></div>');
            $('body').append($selectBoxDashed);
            
            var startX = 0;
            var startY = 0;
            var isSelect = true;
            var _x = null;
            var _y = null;
            var _left   = 0;
            var _top    = 0;
            var _width  = 0;
            var _height = 0;
            var unselectHander = null;
			var select_item_down = false;
            //  框选事件
            $container.on('mousedown', function(eventDown) {
					//console.log("mousedown");
                        //  设置选框可见
                    $selectBoxDashed.css('display', 'block');
                    //  设置选择的标识
                    isSelect = true;
                    //  创建选框节点
                    //  设置选框的初始位置
                    startX = eventDown.x || eventDown.clientX;
                    startY = eventDown.y || eventDown.clientY;
                    $selectBoxDashed.css({
                        left: startX,
                        top : startY
                    });
                    //  根据鼠标移动，设置选框宽高
                    _x = null;
                    _y = null;
                    _left   = 0;
                    _top    = 0;
                    _width  = 0;
                    _height = 0;
                    //  清除事件冒泡、捕获
                    clearBubble(eventDown);
                     //  监听鼠标移动事件
                     
                    $container.on('mousemove', mousemoveCallBack);
                    
					//var unselectHander = setTimeout(function(){
					if(!select_item_down){
						unselectAll();
					}
					//	unselectHander = null;
					//},10);
                });
                
                var unselectAll = function() {
					   $(selector).find('.select-item').each(function() {
                            var $item = $(this);
                                $item.removeClass('selected');
                        });
				}
				
				
                var mousemoveCallBack = function(eventMove) {
                        //console.log(eventMove);
                        //  根据鼠标移动，设置选框的位置、宽高
                        _x = eventMove.x || eventMove.clientX;
                        _y = eventMove.y || eventMove.clientY;
                        //  暂存选框的位置及宽高，用于将 select-item 选中
                        _left   = Math.min(_x, startX);
                        _top    = Math.min(_y, startY);
                        _width  = Math.abs(_x - startX);
                        _height = Math.abs(_y - startY);
                        $selectBoxDashed.css({
                            left  : _left,
                            top   : _top,
                            width : _width,
                            height: _height
                        });
                        //  遍历容器中的选项，进行选中操作
                        $(selector).find('.select-item').each(function() {
                            var $item = $(this);
                            var itemX_pos = $item.prop('offsetWidth') + $item.prop('offsetLeft');
                            var itemY_pos = $item.prop('offsetHeight') + $item.prop('offsetTop');
                            //  判断 select-item 是否与选框有交集，添加选中的效果（ temp-selected ，在事件 mouseup 之后将 temp-selected 替换为 selected）
                            var condition1 = itemX_pos > _left;
                            var condition2 = itemY_pos > _top;
                            var condition3 = $item.prop('offsetLeft') < (_left + _width);
                            var condition4 = $item.prop('offsetTop') < (_top + _height);
                            if (condition1 && condition2 && condition3 && condition4) {
                                $item.addClass('temp-selected');
                            } else {
                                $item.removeClass('temp-selected');
                            }
                        });
                        //  清除事件冒泡、捕获
                        clearBubble(eventMove);
                    };
                
               
                var mouseUpFunc = function() {
                        $(selector).off('mousemove');
                        $(selector)
                            .find('.select-item.temp-selected')
                            .removeClass('temp-selected')
                            .addClass('selected');
                            
                        $selectBoxDashed.css({
                            display : 'none',
                            width : 0,
                            height: 0
                        });
                        if (selectCallback) {
                            selectCallback();
                        }
                    getSelectFiles();
                };


                 $container.on('mouseup', mouseUpFunc);
                 //$container.on('mouseleave', mouseUpFunc);


                //  点选切换选中事件
                $container.on('mousedown', '.select-item', function(e) {
					select_item_down = true;
                });
				
				
                $container.on('mouseup', '.select-item', function(e) {
					//console.log("mousedown .select-item");
					select_item_down = false;
                });
                
                //  点选切换选中事件
                $container.on('click', '.select-item', function(e) {
					//console.log("click .select-item");
                    //  清除事件冒泡、捕获
                    clearBubble(e);
                    if ($(this).hasClass('selected')) {
                        $(this).removeClass('selected');
                    } else {
                        $(this).addClass('selected');
                    }
                    getSelectFiles();
                });
                
                
                //  双击下载
                $container.on('dblclick', '.select-item', function(e) {
                    //  清除事件冒泡、捕获
                    clearBubble(e);
                    downloadFile($(this).attr("data-id"));
                });
                
                //  点选全选全不选
                $("#toggle-all-btn").click(function() {
                    if ($(this).attr('data-all')) {
                        $(this).removeAttr('data-all');
                        $container.find('.select-item').removeClass('selected');
                    } else {
                        $(this).attr('data-all', 1);
                        $container.find('.select-item').addClass('selected');
                    }
                })
        };

    var refeashFiles = function(){
        $.get("get-list.php", function(result){
            //console.log(result);
        var eContainerBox = $('#select-box-container');
        eContainerBox.html("");
        for(var i in result){
            var content = result[i];
            //  http://www.localhost.com/img_scale/?url=https%3a%2f%2ftest.charrobot.com%2ffile_upload%2ffiles%2ficon.jpg&width=20&height=20
            var ext = getFileSuffix(content);
            if(ext=='jpg'||ext=='png'||ext=='gif'){
                var url = domain + baseFilePath + content;
                console.log(url);
                var scale_url = "http://test.charrobot.com/img_scale/?url="+encodeURIComponent(url)+"&width=100&height=100"
                content = "<img src='"+scale_url+"' class='image'/>"+"<div class='image-text'>"+result[i]+"</div>";
            }
            eContainerBox.append("<div class=\"fileDiv select-item\" data-id=\""+result[i]+"\">"+content+"</div>");
        }
        },"json");
    };
    
//  点选全选全不选
    $("#refeash").click(function() {
        refeashFiles();
    })
    
    
    refeashFiles();
    initSelectBox('#select-box-container');
        
    var getSelectFiles = function(){
        var fileArr = [];
        //  点选全选全不选
                $(".container .selected").each(function(){
                fileArr.push($(this).attr("data-id"));
              });
        //console.log(fileArr);
        $("#data").html(JSON.stringify(fileArr));
        return fileArr;
    }; 
    
    
    var deleteFunc = function() {
        var deleteFiles = getSelectFiles();
        if(confirm("是否删除"+deleteFiles.length+"个文件")){
             $.post("delete.php",{'file_arr':deleteFiles}, function(result){
                //console.log(result);
                refeashFiles();
                getSelectFiles();
            },"json");
        }
    };
    
	
	
    var renameFunc = function() {
        var renameFiles = getSelectFiles();
		if(renameFiles.length==0){
			return false;
		}
		if(renameFiles.length>1){
			//以后需要读取文件后缀，批量重命名的时候，后缀要不变
		    alert("暂时只支持重命名一个文件");
			return false;
		}
		var newName=prompt("请输入新的文件名",renameFiles[0]);
		if(!newName){
		return false;
		}
			console.log(newName);
		var name_k_v_arr = [];
		for(var i in renameFiles){
			//console.log(i);
			//console.log(renameFiles[i]);
			name_k_v_arr.push({
				"old_name":renameFiles[i],
				"new_name":newName+(i=='0'?'':('('+i+')')),
			});
		}
			//console.log(name_k_v_arr);
			//console.log(JSON.stringify(name_k_v_arr));
		
		
             $.post("rename.php",{"data":JSON.stringify(name_k_v_arr)}, function(result){
                //console.log(result);
                refeashFiles();
                getSelectFiles();
            },"json");
			
			
    };
	
    var downloadFile = function(name) {
        var url = baseFilePath + name
        window.open(url);
    };
    
    
$(document).keydown(function(event){
if(event.keyCode=='46'){
    deleteFunc();
}else if(event.keyCode=='113'){
    renameFunc();
}
});
    
//  点选全选全不选
    $("#delete").click(deleteFunc);
        

//  点选全选全不选
    $("#rename").click(renameFunc);

})


    /**
     * 获取文件后缀名
     * @param string $str
     */
    function getFileSuffix($str)
    {
        //获取最后一级的文件名
        $pos = $str.lastIndexOf('/');
        if ($pos !== -1) {
            $str = $str.substr( $pos + 1);
        }
        //获取最后一个.后面的内容
        $pos = $str.lastIndexOf('.');
        if ($pos === -1) {
            return false;
        }
        $str = $str.substr( $pos + 1);
        //获取第一个?前面的内容
        $pos = $str.indexOf('?');
        if ($pos === -1) {
            return $str;
        }
        $str = $str.substr( 0, $pos);
        return $str;
    }

</script>



</body>
</html>
